package com.pine.sunshineelder.checkin.service.impl;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;
import com.pine.sunshineelder.checkin.ao.elder.ElderAddAo;
import com.pine.sunshineelder.checkin.ao.elder.ElderModAo;
import com.pine.sunshineelder.checkin.ao.elder.ElderModPasswordAo;
import com.pine.sunshineelder.checkin.service.ElderService;
import com.pine.sunshineelder.checkin.vo.elder.ElderRegisterVo;
import com.pine.sunshineelder.common.StringHelper;
import com.pine.sunshineelder.common.dao.AccountDao;
import com.pine.sunshineelder.common.dao.ElderDao;
import com.pine.sunshineelder.common.dto.QueryResult;
import com.pine.sunshineelder.common.entity.AccountEntity;
import com.pine.sunshineelder.common.entity.ElderEntity;
import com.pine.sunshineelder.common.exception.ThisSystemException;
import com.pine.sunshineelder.common.validator.ValidateHelper;

import lombok.NonNull;

@Service
public class ElderServiceImpl implements ElderService, StringHelper {
	@Autowired
	private ElderDao edao;
	@Autowired
	private AccountDao adao;

	@Override
	public ElderEntity addElder(@NonNull ElderAddAo ao) throws Exception {
		// 2.业务处理
		if (adao.selectExist("account", ao.getAccount())) {
			throw new ThisSystemException("acount.exists", "账号已存在");
		}
		if (edao.selectExist("no", ao.getNo())) {
			throw new ThisSystemException("no.exists", "编号已存在");
		}
		// 3组装结果
		ElderEntity ee = new ElderEntity();
		String id = uuid();
		ee.setId(id);
		ee.setNo(ao.getNo());
		ee.setHeight(ao.getHeight());
		ee.setWeight(ao.getWeight());
		ee.setBooldType(ao.getBooldType());
		ee.setMarriage(ao.getMarriage());
		ee.setMedicalRecord(ao.getMedicalRecord());
		ee.setPrivatePhone(ao.getPrivatePhone());
		ee.setAddress(ao.getAddress());
		ee.setBirthday(ao.getBirthday());
		ee.setIdCard(ao.getIdCard());
		ee.setImage(ao.getImage());
		ee.setMale(ao.getMale());
		ee.setName(ao.getName());
		ee.setAccount(ao.getAccount());
		ee.setRemark(ao.getRemark());
		ee.setEnterTime(ao.getEnterTime());
		AccountEntity ae = new AccountEntity();
		ae.setId(id);
		ae.setAccount(ao.getAccount());
		ae.setName(ao.getName());
		ae.setPassword("888888");
		ae.setCreateUserId(ao.getCreateUserId());
		ae.setFlag(0);
		ae.setRole(4);
		edao.insert(ee);
		adao.insert(ae);

		return ee;
	}

	@Override
	public void deleteElder(String id) throws Exception {
		// 1 验证清理参数
		id = ValidateHelper.$("id", id);
		// 2执行业务逻辑
		adao.delete(id);
	}

	@Override
	public ElderEntity modifyElder(String id, ElderModAo ao) throws Exception {
		// 1 验证清理参数
		id = ValidateHelper.$("id", id);

		// 2执行业务逻辑
		ElderEntity old = edao.selectById(id);

		if (old == null) {
			throw new ThisSystemException("id.not-exisits", "非法id");
		}
		Map<String, Object> eupdateMap = new HashMap<String, Object>();
		Map<String, Object> aupdateMap = new HashMap<String, Object>();

		// 2.1 长度
		String newAccount = trimAsNull(ao.getAccount());
		if (newAccount != null) {
			if (!Objects.equals(old.getAccount(), newAccount)) {
				ValidateHelper.assertLength("账号", newAccount, 6, 16);
				ValidateHelper.assertMatch("账号只能是字母和数字组成的6-16位", newAccount, "[0-9a-zA-Z]{6,16}");
				// 2.2 账号是否存在
				if (adao.existAccount(newAccount)) {
					throw new ThisSystemException("acount.exists", "账号已存在");
				}
				// 修改旧对象
				old.setAccount(newAccount);
				// 保存要修改的字段
				aupdateMap.put("account", newAccount);
			}
		}
		// 2.2 名字
		String newName = trimAsNull(ao.getName());
		if (newName != null) {
			if (!Objects.equals(old.getName(), newName)) {
				ValidateHelper.assertLength("名字", newName, 2, 16);
				ValidateHelper.assertMatch("名字必须是中文2-16位", newName, "[\u4e00-\u9fa5·]{2,16}");
				old.setName(newName);
				aupdateMap.put("name", newName);
			}
		}
		// 2.3相片
		String newImage = trimAsNull(ao.getImage());
		if (newImage != null) {
			if (!Objects.equals(old.getName(), newImage)) {
				old.setImage(newImage);
				eupdateMap.put("image", newImage);
			}
		}
		// 2.4height
		if (ao.getHeight() != null) {
			Integer newHeight = Integer.parseInt(ao.getHeight());
			if (old.getHeight() != newHeight) {
				old.setHeight(newHeight);
				eupdateMap.put("height", newHeight);
			}
		}

		// 2.5weight
		if (ao.getWeight() != null) {
			Integer newWeight = Integer.parseInt(ao.getWeight());
			if (old.getWeight() != newWeight) {
				old.setWeight(newWeight);
				eupdateMap.put("weight", newWeight);
			}
		}
		// 血型 0-O型 1-A型 2-B型 3-AB型
		if (ao.getBooldType() != null) {
			if (old.getBooldType() != ao.getBooldType()) {
				old.setBooldType(ao.getBooldType());
				eupdateMap.put("booldType", ao.getBooldType());
			}
		}
		// 婚姻状况0-未婚 1-已婚 2-离异 3-丧偶
		if (ao.getMarriage() != null) {
			if (old.getMarriage() != ao.getMarriage()) {
				old.setMarriage(ao.getMarriage());
				eupdateMap.put("marriage", ao.getMarriage());
			}
		}
		// 以往历史医疗记录
		if (ao.getMedicalRecord() != null) {
			if (!Objects.equals(old.getMedicalRecord(), ao.getMedicalRecord())) {
				old.setMedicalRecord(ao.getMedicalRecord());
				eupdateMap.put("medicalRecord", ao.getMedicalRecord());
			}
		}
		// 入院时间
		if (ao.getEnterTime() != null) {
			if (old.getEnterTime().compareTo( ao.getEnterTime())!=0) {
				old.setEnterTime(ao.getEnterTime());
				eupdateMap.put("enterTime", ao.getEnterTime());
			}
		}
		// 私人电话
		if (ao.getPrivatePhone() != null) {
			if (!Objects.equals(old.getPrivatePhone(), ao.getPrivatePhone())) {
				old.setPrivatePhone(ao.getPrivatePhone());
				eupdateMap.put("privatePhone", ao.getPrivatePhone());
			}
		}
		// 家庭地址
		if (ao.getAddress() != null) {
			if (!Objects.equals(old.getAddress(), ao.getAddress())) {
				old.setAddress(ao.getAddress());
				eupdateMap.put("address", ao.getAddress());
			}
		}
		// 身份证号
		if (ao.getIdCard() != null) {
			if (!Objects.equals(old.getIdCard(), ao.getIdCard())) {
				old.setIdCard(ao.getIdCard());
				eupdateMap.put("idCard", ao.getIdCard());
			}
		}
		// 出生日期
		if (ao.getBirthday() != null) {
			if (old.getBirthday().compareTo(ao.getBirthday())!=0) {
				old.setBirthday(ao.getBirthday());
				eupdateMap.put("birthday", ao.getBirthday());
			}
		}
		// 备注
		if (ao.getRemark() != null) {
			if (!Objects.equals(old.getRemark(), ao.getRemark())) {
				old.setRemark(ao.getRemark());
				eupdateMap.put("remark", ao.getRemark());
			}
		}
		// 2.3 进行实际的修改
		if (!aupdateMap.isEmpty()) {
			adao.update(id, aupdateMap);
		}
		if (!eupdateMap.isEmpty()) {
			edao.update(id, eupdateMap);
		}
		// 3组装业务结果
		return old;
	}

	@Override
	public void modifyPassword(String id, ElderModPasswordAo ao) throws Exception {
		// 1 验证清理参数
		id = ValidateHelper.$("id", id);
		String oldPassword = ValidateHelper.$("旧密码", ao.getOldPassword());
		String newPassword = ValidateHelper.$("新密码", ao.getNewPassword());
		String newPasswordConfirm = ValidateHelper.$("新密码验证", ao.getNewPasswordConfirm());
		// 2执行业务逻辑
		ElderEntity old = edao.selectById(id);

		if (old == null) {
			throw new ThisSystemException("id.not-exisits", "非法id");
		}
		if (Objects.equals(newPassword, oldPassword)) {
			throw new ThisSystemException("password.not-same", "新旧密码一致");
		}
		// 2.3密码相等
		if (!Objects.equals(newPassword, newPasswordConfirm)) {
			throw new ThisSystemException("password.not-same", "两次密码不一致");
		}
		// 2.2密码符合要求
		ValidateHelper.assertLength("密码", newPassword, 6, 16);
		ValidateHelper.assertAlphanumeric("密码", newPassword);
		// 2.1验证账户密码是否匹配
		if (Objects.equals(old.getPassword(), oldPassword)) {
			throw new ThisSystemException("account.password.not.match", "账号密码不匹配");
		}
		Map<String, Object> map = new HashMap<String, Object>(4, 1);
		map.put("password", newPassword);
		adao.update(id, map);
	}

	@Override
	public QueryResult<ElderEntity> queryByKey(String key, Integer pageNo, Integer pageSize) throws Exception {
		key = trimAsNull(key);
		if (key != null) {
			key = "%" + key + "%";
		}
		System.out.println(key+" "+pageNo+" "+pageSize);
		List<ElderEntity> rows = edao.selectByKey(key, pageNo, pageSize);

		PageInfo pageInfo = new PageInfo(rows);

		int totalRows = (int) pageInfo.getTotal();

		QueryResult<ElderEntity> result = new QueryResult<ElderEntity>();
		result.setPageNo(pageNo);
		result.setPageSize(pageSize);
		result.setTotalRows(totalRows);
		result.setRows(rows);

		return result;
	}

	@Override
	public ElderEntity queryById(String id) throws Exception {
		// 1 验证清理参数
		id = ValidateHelper.$("id", id);
		// 2执行业务逻辑
		ElderEntity elder = edao.selectById(id);
		if (elder == null) {
			throw new ThisSystemException("id.not-exisits", "非法id");
		}
		return elder;
	}

}
